class Solution:
    def spiralOrder(self, matrix):
        if not matrix:
            return []
        result = []
        top, bottom = 0, len(matrix)-1
        left, right = 0, len(matrix[0])-1
        while top <= bottom and left <= right:
            # 向右走
            for i in range(left, right+1):
                result.append(matrix[top][i])
            top += 1
            # 向下走
            for j in range(top, bottom+1):
                result.append(matrix[j][right])
            right -= 1
            # 向左走（确保还有行）
            if top <= bottom:
                for i in range(right, left-1, -1):
                    result.append(matrix[bottom][i])
                bottom -= 1
            # 向上走（确保还有列）
            if left <= right:
                for j in range(bottom, top-1, -1):
                    result.append(matrix[j][left])
                left += 1
        return result
        
if __name__ == '__main__':
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    print(Solution().spiralOrder(matrix))